<template>
  <div class="page-body">
    <DetailPageHeader @clickHome="clickHome" @clickLock="switchShowLock" />
    <div class="page-content m-10">
      <div class="left">
        <!-- tabs -->
        <div class="left_1">
          <div class="tabs">
            <div
              @click="switchLeftTabsIndex(0)"
              :class="[leftTabsIndex === 0 && 'active']"
            >
              已下单商品
            </div>
            <div
              @click="switchLeftTabsIndex(1)"
              :class="[leftTabsIndex === 1 && 'active']"
            >
              取单列表({{ commonStore.getGuadanList.length }})
            </div>
          </div>
          <div
            v-if="!leftTabsIndex"
            @click="onClickGuadan"
            class="guadan flex items-center p-r-20"
          >
            <text>一键挂单</text>
            <text class="iconfont icon-caidan font-size-26 m-l-4" />
          </div>
        </div>
        <div class="h-0 flex-1">
          <WCheckGoods
            :list="leftTabsIndex ? commonStore.getGuadanList : checkGoods"
            :checkIndex="checkGoodsIndex"
            :showType="leftTabsIndex"
            @clickGoods="(i, item) => (checkGoodsIndex = i)"
            @onAllDeleteCheckGoods="onAllDeleteCheckGoods"
            @onDeleteGoodsItem="onDeleteGoodsItem"
            @numberChange="goodsNumberChange"
          />
        </div>
        <!-- 合计 -->
        <div v-if="!leftTabsIndex" class="left_4">
          <div class="total-price">
            <text class="font-size-18">￥</text>
            <text class="font-size-24">{{ checkTotal }}</text>
          </div>
          <div class="yj-bt">原价付</div>
          <div @click="SettlementPopupRef.open()" class="js-bt">结算({{ checkGoods.length }})</div>
        </div>

        <div v-else class="">
          <div @click="onClickQudan" class="qd-bt">取单</div>
        </div>
      </div>
      <div class="right" style="background-color: #eff5fb">
        <WSearchInput
          v-model="searchValue"
          class="p-y-9 p-x-14 bg-color"
          placeholder="扫码或输入商品编码/商品条码/PLU码/商品首字母拼音"
          :active="inputActive"
          saomaType="searchGoods"
          isCancelBtn
          @clickInput="clickSearchInput"
          @cancelBt="clickSearchBt"
        />

        <div class="right-content">
          <div class="right-content-left flex-1 w-0" style="position: relative">
            <!-- 二级分类 -->
            <div v-if="cartList_2.length" class="flex items-center">
              <scroll-view scroll-x class="flex-1 w-0">
                <div class="cart-items" v-if="!inputActive">
                  <div
                    v-for="(item, i) in cartList_2"
                    :key="item"
                    @click="checkCart_2(i)"
                    :class="['item', i === cartIndex_2 && 'active']"
                  >
                    {{ item.name }}
                  </div>
                </div>
              </scroll-view>

              <div
                @click="switchCatPopup"
                v-if="!inputActive"
                class="iconfont icon-quanbufenzu font-size-22 p-x-15 m-b-10"
              ></div>
            </div>
            <div
              v-if="catPopup && !inputActive"
              @click="switchCatPopup"
              class="two-cat-abs"
            >
              <div @click.stop class="cat-abs-content p-t-10 p-l-10">
                <div class="cart-items flex-wrap">
                  <div
                    v-for="(item, i) in cartList_2"
                    :key="item"
                    @click="checkCart_2(i)"
                    :class="['item  m-b-10', i === cartIndex_2 && 'active']"
                  >
                    {{ item.name }}
                  </div>
                </div>
              </div>
            </div>

            <!-- 商品 -->
            <scroll-view scroll-y class="flex-1 h-0">
              <div class="h-100">
                <WSearchGoods
                  @clickGood="clickGood"
                  :list="inputActive ? searchGoods : goodsList"
                  :inputActive="inputActive"
                  :searchValue="searchValue"
                />
              </div>
            </scroll-view>
          </div>

          <div v-if="!inputActive" class="right-content-right">
            <div
              v-for="(item, i) in cartList_1"
              :key="i"
              @click="checkCart_1(i)"
              :class="['item u-line-1', i == cartIndex_1 && 'active']"
            >
              {{ item.name }}
            </div>
          </div>
        </div>

        <WKeyboard
          class="p-x-9 p-y-20"
          style="background-color: #e2e5ea"
          ref="WKeyboardRef"
          width="64"
          height="54"
          gap="9rpx"
          numWidth="90"
          numHeight="54"
          numGap="15rpx"
          v-model="searchValue"
          @inputChange="inputChange"
        />

        <QudanPopup
          :showPopup="leftTabsIndex"
          :list="commonStore.getGuadanList[checkGoodsIndex]?.goods || []"
          ref="QudanPopupRef"
        />
      </div>
    </div>
  </div>

  <DiyModal ref="diyModalRef" />

  <SettlementPopup ref="SettlementPopupRef" />
</template>
<script setup>
import { onLoad } from "@dcloudio/uni-app";
import { ref, computed } from "vue";
import utils from "@/utils/index";
import WSearchGoods from "./components/WSeachGoods.vue";
import WCheckGoods from "./components/WCheckGoods.vue";
import QudanPopup from "./components/QudanPopup.vue";
import allApi from "@/api/index";
import SettlementPopup from './components/SettlementPopup.vue'
const SettlementPopupRef = ref()
import { useCommonStore } from "../store/common";
import dayjs from "dayjs";
const commonStore = useCommonStore();
// modal弹框实例
const diyModalRef = ref();
// 已下单商品
const checkGoodsIndex = ref(0);
const checkGoods = ref([]);
const leftTabsIndex = ref(0);
// 搜索value
const searchValue = ref("");
// 挂单列表
const guadanList = ref([]);
// 可选商品
const goodsList = ref([]);
// 搜索到的商品
const searchGoods = ref([]);
// 键盘实例
const WKeyboardRef = ref();
const inputActive = ref(false);
// 二级分类是否展开
const catPopup = ref(false);

// 一级分类索引
const cartIndex_1 = ref(0);
//  二级分类索引
const cartIndex_2 = ref(0);
const cartList_1 = ref([]);
const cartList_2 = computed(() => {
  console.log(cartIndex_1.value, cartList_1.value, "123");
  if (cartList_1.value.length) {
    return cartList_1.value[cartIndex_1.value].bundleDOS;
  }
  return [];
});

const checkTotal = computed(() => {
  let total = 0;
  checkGoods.value.forEach((item) => {
    total = utils.FloatAdd(
      total,
      utils.FloatMul(item.num, item.promotionPrice || item.retailPrice)
    );
  });
  return total.wtoFixed(2);
});

onLoad(() => {
  commonStore.setSaomaType("searchGoods");

  getCartList();
});



async function getCartList() {
  const res = await allApi.erp.salePanelBundle.getByPosId(commonStore.posId);
  cartList_1.value = res.data;
  getGoods();
}

async function getGoods() {
  const res = await allApi.erp.salePanelSkus.selectSkusList({
    bundleId:
      cartIndex_2.value > -1
        ? cartList_2.value[cartIndex_2.value].id
        : cartList_1.value[cartIndex_1.value].id,
    merchantId: commonStore.merchantId,
  });
  goodsList.value = res.data;
}

async function getSearchGoods(type = "SPECIFY") {
  const res = await allApi.erp.productSku.selectProductSkuByCombination(
    {
      inputCode: searchValue.value,
      combinationTypeEnum: type, //SCAN扫码，SPECIFY手动输入
    },
    {
      showLoading: false,
      showError: false,
    }
  );
  searchGoods.value = res.data;
}

function switchCatPopup() {
  console.log(catPopup.value);
  catPopup.value = !catPopup.value;
}

function checkCart_1(index) {
  cartIndex_1.value = index;
  if (cartList_1.value[index].bundleDOS.length) {
    cartIndex_2.value = 0;
  } else {
    cartIndex_2.value = -1;
  }
  getGoods();
}
function checkCart_2(index) {
  cartIndex_2.value = index;
  getGoods();
}

function switchLeftTabsIndex(index) {
  leftTabsIndex.value = index;
  checkGoodsIndex.value = 0;
}

// 键盘change
function inputChange(v) {
  // searchValue.value = v;
  getSearchGoods();
}
// 点击searchinput
function clickSearchInput() {
  inputActive.value = true;
  WKeyboardRef.value.switchShowJianpan(true);
}
// 点击取消按钮
function clickSearchBt() {
  inputActive.value = false;
  searchValue.value = "";
  WKeyboardRef.value.switchShowJianpan(false);
}

async function onAllDeleteCheckGoods() {
  if (checkGoods.value.length == 0) {
    uni.showToast({
      title: "没有可清空的商品",
      icon: "none",
    });
    return;
  }
  await diyModalRef.value.open({
    contentText: "本次操作将清空列表全部商品，是否确定清空？",
    confirmText: "确定清空",
  });
  checkGoods.value = [];
  checkGoodsIndex.value = 0;
}
// 点击home
async function clickHome() {
  if (checkGoods.value.length) {
    await diyModalRef.value.open({
      contentText: "回到首页会清空当前商品列表及会员信息，确定要返回首页",
    });
  }
  utils.toUrl("/pages/home/home", "redirectTo");
}
async function clickGood(item) {
  let goods = checkGoods.value.find((it) => item.skuId == it.id);
  if (!goods) {
    const { data } = await allApi.erp.productSku.selectProductSkuByCombination({
      inputCode: item.skuId,
      combinationTypeEnum: "SPECIFY", //SCAN扫码，SPECIFY手动输入
    });
    goods = data;
  }

  addCheckGoods(goods);
}
function addCheckGoods(data) {
  let num = 1;
  let fIndex = checkGoods.value.findIndex((it) => data.id == it.id);
  if (fIndex > -1) {
    num = checkGoods.value[fIndex].num + 1;
    checkGoods.value.splice(fIndex, 1);
  }
  checkGoods.value.unshift({
    ...data,
    num,
  });
  checkGoodsIndex.value = 0;
  console.log(checkGoods.value);
  utils.sendDataToSecondScreen({
    data: JSON.parse(JSON.stringify(checkGoods.value)),
    type: "goods",
  });
}

function onDeleteGoodsItem(index) {
  let i = checkGoodsIndex.value - 1;
  checkGoodsIndex.value = i < 0 ? 0 : i;

  if (leftTabsIndex.value) {
    guadanList.value.splice(index, 1);
  } else {
    checkGoods.value.splice(index, 1);

    utils.sendDataToSecondScreen({
      data: JSON.parse(JSON.stringify(checkGoods.value)),
      type: "goods",
    });
  }
}

async function goodsNumberChange(v) {
  checkGoods.value[checkGoodsIndex.value].num = v.value;
  utils.sendDataToSecondScreen({
    data: JSON.parse(JSON.stringify(checkGoods.value)),
    type: "goods",
  });
}

function onClickGuadan() {
  if (checkGoods.value.length == 0) {
    uni.showToast({
      title: "当前无挂单商品",
      icon: "none",
    });
    return;
  }
  let guadanList = commonStore.getGuadanList || [];
  guadanList.unshift({
    date: dayjs(new Date()).format("YYYY-MM-DD HH:mm:ss"),
    goods: checkGoods.value,
    total: checkTotal.value,
    mermberPhone: "",
  });
  commonStore.setGuadanList(guadanList);

  checkGoods.value = [];
  checkGoodsIndex.value = 0;
  utils.sendDataToSecondScreen({
    data: [],
    type: "goods",
  });
}

async function onClickQudan() {
  let guadanList = commonStore.getGuadanList || [];
  let qudanIndex = checkGoodsIndex.value;
  if (checkGoods.value.length) {
    const isZancun = await diyModalRef.value
      .open({
        contentText: "取单后，当前已下单商品列表中是否需要清空？",
        confirmText: "确定清空",
        cancelText: "挂单暂存",
      })
      .catch((err) => err);
    console.log(isZancun, "isZancun");
    if (!isZancun) {
      // 处理挂单
      guadanList.unshift({
        date: dayjs(new Date()).format("YYYY-MM-DD HH:mm:ss"),
        goods: checkGoods.value,
        total: checkTotal.value,
        mermberPhone: "",
      });
      qudanIndex += 1;
    }
  }
  checkGoods.value = guadanList[qudanIndex].goods;
  guadanList.splice(qudanIndex, 1);
  commonStore.setGuadanList(guadanList);

  checkGoodsIndex.value = 0;
  leftTabsIndex.value = 0;

  utils.sendDataToSecondScreen({
    data: checkGoods.value,
    type: "goods",
  });
}

// 扫码枪逻辑
uni.$on("sendCode", sendCode);
async function sendCode(e) {
  // 不是当前输入框的扫码
  if (commonStore.saomaType !== "searchGoods") return;

  // 搜索商品，添加购物车，如果没有提示商品不存在
  const { data } = await allApi.erp.productSku.selectProductSkuByCombination({
    inputCode: e,
    combinationTypeEnum: "SCAN", //SCAN扫码，SPECIFY手动输入
  });
  addCheckGoods(data);
  // setTimeout(() => {
  //   searchValue.value = "";

  // }, 5000);
}
</script>
<style lang="scss" scoped>
.page-body {
  display: flex;
  flex-direction: column;
  height: 100vh;
  background: #f0f2f5;
  .page-content {
    display: flex;
    flex: 1;
    height: 0;
    position: relative;
    > div {
      border-radius: 14px;
      background: $uni-text-color-inverse;
      border: 1px solid $uni-border-color-1;
      overflow: hidden;
    }
    .left {
      display: flex;
      flex-direction: column;

      width: 510rpx;
      margin-right: 10rpx;
      .left_1 {
        display: flex;
        justify-content: space-between;
        height: 46rpx;
        border-bottom: 1px solid $uni-border-color-1;

        .tabs {
          display: flex;
          // transform: translateY(1px);
          text-align: center;
          > div {
            background: #f2f6fc;
            color: $uni-text-color-3;
            font-size: 16rpx;
            line-height: 46rpx;
            min-width: 134rpx;
            border: 1px solid $uni-border-color-1;
            border-left: 0;
            border-top: 0;
            border-bottom: 0;
          }
          .active {
            background: transparent;
            color: $uni-color-primary;
          }
        }
        .guadan {
          flex: 1;
          width: 0;
          display: flex;
          align-items: center;
          justify-content: flex-end;
          font-size: 16rpx;
          color: $uni-color-primary;
        }
      }

      .left_4 {
        display: flex;
        box-shadow: 0px 8rpx 20rpx rgba($color: #000000, $alpha: 0.3);
        // box-shadow: 0px 13.33px 33.33px  #000000;
        height: 60rpx;

        .total-price {
          flex: 1;
          width: 0;
          color: $uni-text-color-price;
          font-weight: 700;
          padding-left: 20rpx;
          line-height: 60rpx;
        }
        .yj-bt {
          width: 107rpx;
          line-height: 60rpx;
          border-left: 1px solid $uni-border-color-1;
          text-align: center;
          font-size: 18rpx;
          font-weight: 700;
          color: $uni-text-color-2;
        }
        .js-bt {
          width: 133rpx;
          line-height: 60rpx;
          text-align: center;
          background: $uni-color-primary;
          font-size: 18rpx;
          font-weight: 700;
          color: $uni-text-color-inverse;
        }
      }
      .qd-bt {
        margin: 20rpx auto;
        width: 454rpx;
        height: 50rpx;
        text-align: center;
        line-height: 50rpx;
        border-radius: 8rpx;
        background-color: $uni-color-primary;
        color: $uni-text-color-inverse;
        font-size: 18rpx;
        font-weight: 700;
      }
    }
    .right {
      flex: 1;
      width: 0;
      display: flex;
      flex-direction: column;

      position: relative;

      .right-content {
        display: flex;
        flex: 1;
        height: 0;
        .right-content-left {
          background: #eff5fb;
          padding: 14rpx 0 14rpx 14rpx;
          display: flex;
          flex-direction: column;
          .cart-items {
            width: 100%;
            display: flex;
            overflow-x: auto;
            .item {
              padding: 8rpx 13rpx;
              border-radius: 4rpx;
              border: 1px solid $uni-border-color-1;
              font-size: 16rpx;
              line-height: 1;
              color: $uni-text-color-3;
              margin-right: 10rpx;
              margin-bottom: 10rpx;
              white-space: nowrap;
            }
            .active {
              // background: $uni-color-primary;
              color: $uni-color-primary;
              border-color: $uni-color-primary;
            }
          }

          .two-cat-abs {
            position: absolute;
            left: 0;
            top: 0;
            right: 0;
            bottom: 0;
            z-index: 888;
            background: rgba($color: #000000, $alpha: 0.3);
            .cat-abs-content {
              background: $uni-bg-color;
              min-height: 210rpx;
            }
          }
        }
        .right-content-right {
          background: #ebeef5;
          width: 82rpx;
          overflow-y: scroll;
          .item {
            line-height: 54rpx;
            font-size: 16rpx;
            text-align: center;
            background: $uni-bg-color;
            border-bottom: 1px solid $uni-border-color-1;
          }
          .active {
            border-left: 4rpx solid $uni-color-primary;
            color: $uni-color-primary;
          }
        }
      }
    }
  }
}
</style>
